﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using Microsoft.Win32;
using PagedList;
using SelfMadeMillionaire.Core.Entities;
using SelfMadeMillionaire.Core.Enums;
using SelfMadeMillionaire.Core.Services;
using SelfMadeMillionaire.Web.Infrastructure.ViewModels.EmailSend;

namespace SelfMadeMillionaire.Web.Infrastructure.Controllers.Admin
{
    public class EmailSendController : AdminController
    {

        private IEmailSendService _emailSendService;
        private List<string> newRecipientList = new List<string>();

        public EmailSendController(IEmailSendService emailSendService)
        {
            _emailSendService = emailSendService;
        }

        public ActionResult Index(int? discount, bool? isPercent, string promoCode, DateTime? effectiveDate, DateTime? expirationDate, int? product)
        {
            var model = new EmailSendView();
            if (discount != null && isPercent != null && product != null)
            {
                if (product == (int)PromotionProduct.AllSubscriptionLevels)
                {
                    model.IsFreeSubscribers = true;
                }
                else if (product == (int)PromotionProduct.GoldSubscription)
                {
                    model.IsGold = true;
                }
                else if (product == (int)PromotionProduct.SilverSubscription)
                {
                    model.IsSilver = true;
                }

                model.Subject = "Special promotion for Self-Made Millionaire subscribers";
                model.Body = CreateSpecialPromotionSelfMadeMale(discount, isPercent, promoCode, effectiveDate,
                    expirationDate);
            }

            
           
            return View(model);
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Index(EmailSendView model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            if (String.IsNullOrEmpty(model.AdditRecipients) && !model.IsFreeSubscribers && !model.IsSilver && !model.IsGold && !model.IsPlatinum)
            {
                ModelState.AddModelError("AdditRecipients", "field 'To' or 'Additional recipients'  is required");
                return View(model);
            }

            if ((!string.IsNullOrEmpty(model.AdditRecipients)) && (!IsValidEmail(model.AdditRecipients)))
            {
                ModelState.AddModelError("AdditRecipients", "Not all mails are correct");
                model.AdditRecipients = String.Join("; ", newRecipientList.ToArray());
                return View(model);
            }
            
            var date = DateTime.Now;
            var emailSend = new EmailSend()
            {
                AdditRecipients = String.Join("; ", newRecipientList.ToArray()),
                Subject = model.Subject??"",
                Body = model.Body??"",
                IsFreeSubscribers = model.IsFreeSubscribers,
                IsSilver = model.IsSilver,
                IsGold = model.IsGold,
                IsPlatinum = model.IsPlatinum,
                Status = (byte)StatusType.Active,
                CreationDate = date,
                SentDate = date
            };

            EmailSend saveEmailSend = _emailSendService.Add(emailSend);
            if (saveEmailSend == null)
            {
                return View(model);
            }

            return RedirectToAction("ViewSendEmail", new {id = saveEmailSend.ID});
        }

        public ActionResult ViewSendEmail(int? page, int id = 0)
        {
            if (id == 0)
            {
                return RedirectToAction("Index");
            }

            var emailExist = _emailSendService.Get(id);
            
            if (emailExist==null)
            {
                return RedirectToAction("Index");
            }
            var model = new EmailSendView()
            {
                ID = emailExist.ID,
                AdditRecipients = emailExist.AdditRecipients,
                Subject = emailExist.Subject,
                Body = emailExist.Body,
                IsFreeSubscribers = emailExist.IsFreeSubscribers,
                IsSilver = emailExist.IsSilver,
                IsGold = emailExist.IsGold,
                IsPlatinum = emailExist.IsPlatinum,
                Status = emailExist.Status,
                CreationDate = emailExist.CreationDate,
                SentDate = emailExist.SentDate
            };

            model.SendTo = CreateSendToList(emailExist);
            if (page.HasValue)
                model.Page = page.Value;

            return View(model);
        }

        public ActionResult Resend(int? page, int id = 0)
        {
            var resendEmail = new EmailSend();
            
            if(id!=0)
            {
                resendEmail = _emailSendService.Get(id);
            }
            if (resendEmail != null )
            {
                resendEmail.SentDate = DateTime.Now;
                resendEmail.Status = (byte) StatusType.Active;
            }
            
            var updateEmail = _emailSendService.Update(resendEmail);

            return RedirectToAction("EmailSendList", new { page = page });
        }

        public ActionResult EmailSendList(int? page, string sort)
        {
            int pageIndex = page > 0? page.Value : 1;
            int pageSize = 10;

            //var emailsList = _emailSendService.GetAll().ToList();

            var model = new EmailSendList()
            {
                SortOrder = sort
            };

            IEnumerable<EmailSend> list = _emailSendService.GetAll();
            if (!string.IsNullOrEmpty(sort))
            {
                string[] sortArr = sort.Split(',');
                if (sortArr[1] == "0")
                {

                    switch (sortArr[0])
                    {
                        case "0":
                            list = list.OrderBy(i => i.Subject);
                            break;
                        case "1":
                            list = list.OrderBy(i => i.SendTo);
                            break;
                        case "2":
                            list = list.OrderBy(i => i.AdditRecipients);
                            break;
                        case "3":
                            list = list.OrderBy(i => i.SentDate);
                            break;
                    }

                }
                else
                {
                    switch (sortArr[0])
                    {
                        case "0":
                            list = list.OrderByDescending(i => i.Subject);
                            break;
                        case "1":
                            list = list.OrderByDescending(i => i.SendTo);
                            break;
                        case "2":
                            list = list.OrderByDescending(i => i.AdditRecipients);
                            break;
                        case "3":
                            list = list.OrderByDescending(i => i.SentDate);
                            break;
                    }
                }
            }
            model.SentItem = list.ToList().ToPagedList(pageIndex, pageSize);
            foreach (var item in model.SentItem)
            {
                item.SendTo = CreateSendToList(item);
            }

            if (Request.IsAjaxRequest())
                return PartialView("EmailSendList", model);
                        
            return View(model);
        }

        public ActionResult SendPromotion(int discount, bool isPercent, string promoCode, DateTime effectiveDate, DateTime expirationDate, int product)
        {
            var sendEmail = new EmailSendView();
            if (product == (int) PromotionProduct.AllSubscriptionLevels)
            {
                sendEmail.IsFreeSubscribers = true;
            }
            else if (product == (int)PromotionProduct.GoldSubscription)
            {
                sendEmail.IsGold = true;
            }
            else if (product == (int)PromotionProduct.SilverSubscription)
            {
                sendEmail.IsSilver= true;
            }

            sendEmail.Subject = "Special promotion for Self-Made Millionaire subscribers";
            sendEmail.Body = CreateSpecialPromotionSelfMadeMale(discount, isPercent, promoCode, effectiveDate,
                expirationDate);

            return RedirectToAction("Index", sendEmail);
        }

        private string CreateSendToList(EmailSend model)
        {
            string sendTo = string.Empty;

            var listSendTo = new List<string>();
            if(model.IsFreeSubscribers)
                listSendTo.Add("Free Subscribers");
            if (model.IsSilver)
                listSendTo.Add("Silver");
            if (model.IsGold)
                listSendTo.Add("Gold");
            if (model.IsPlatinum)
                listSendTo.Add("Platinum");

            sendTo = String.Join(", ", listSendTo.ToArray()); 

            return sendTo;
        }

        private string CreateSpecialPromotionSelfMadeMale(int? discount, bool? isPercent, string promoCode, DateTime? effectiveDate, DateTime? expirationDate)
        {
            string body = string.Empty;

            body = "<p>Dear Self-Made Millionaire Subscriber," +
                   "</p>\r\n<p>&nbsp;</p>" +
                   "\r\n<p>Please use a special promotion code: " + promoCode + " to get " + discount + (isPercent==true?"%":" dollars")+" off current price when you renew</p>" +
                   "\r\n<p>(extend) you membership for one more year. The subscription rates will go up after " + (expirationDate.HasValue?expirationDate.Value.ToShortDateString():"") + " so</p>" +
                   "\r\n<p>make sure you lock your current rate with additional discount of " + discount + (isPercent == true ? "%" : "dollars") + " - what a return!</p>" +
                   "</p>\r\n<p>&nbsp;</p>" + 
                   "\r\n<p>Feel free to contact us with any questions," +
                   "</p>\r\n<p>&nbsp;</p>" +
                   "</p>\r\n<p>- Self-Made Millionaire Academy</p>"; 

            return body;
        }

        public bool IsValidEmail(string emailsStr)
        {
            if (string.IsNullOrEmpty(emailsStr)) return true;

            var recipientList = new List<string>();
            recipientList = emailsStr.Split(new char[] { ' ', ',', ';', '<', '>', '"' }).ToList();
            foreach (var email in recipientList)
            {
                if (email != "")
                {
                    var eml = email.Trim().ToLower();
                    var isValid = Regex.IsMatch(eml, @"\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}\z")
                        && Regex.IsMatch(eml, @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*");

                    if (!isValid) return false;

                    newRecipientList.Add(eml);
                }
                
            }

            return true;
        }

    }
}
